package com.wu.flandre.component.interceptor;

import com.wu.flandre.annotation.ValidateAccessToken;
import com.wu.flandre.exceptions.UnauthorizedException;
import com.wu.flandre.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JwtTokenHandlerInterceptor <br/>
 *
 * @author 50816 <br/>
 * @date 2019/12/15 0:49 <br/>
 */
public class JwtTokenHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    JwtUtil jwtUtil;

    private static final String USER_ID = "userId";

    private static final String OPTIONS = "options";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String mail = request.getParameter("mail");
        if (OPTIONS.equals(request.getMethod().toLowerCase())) {
            return true;
        }
        //获取请求执行方法的注解
        ValidateAccessToken validateAccessToken = ((HandlerMethod) handler).getMethodAnnotation(ValidateAccessToken.class);
        //判断注解的属性是否为true
        if (validateAccessToken.value()) {
            //true验证token
            String access_token = request.getHeader("access_token");
            if (access_token == null) {
                throw new UnauthorizedException("用户缺少Access_Token,请登录");
            } else {
                Claims claims = jwtUtil.verifyJwt(access_token);
                if (null == claims.get(USER_ID)) {
                    throw new UnauthorizedException("用户Access_Token无效,请重新登录");
                } else {
                    Integer authNum = validateAccessToken.authority().getAuthNum();
                    Integer user_authority = Integer.valueOf(claims.get("authority").toString());
                    if (user_authority >= authNum) {
                        return true;
                    } else {
                        throw new UnauthorizedException("用户权限不足,无法调用该api");
                    }
                }
            }
        } else {
            //false不需要验证,直接通过
            return true;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
